package hot100;

import java.net.Inet4Address;
import java.util.HashMap;
import java.util.Map;

public class Solution105 {

    public TreeNode dfs(int[] preorder, Map<Integer, Integer> inorderMap, int preorderLeft, int preorderRight,
        int inorderLeft, int inorderRight) {
        if (preorderLeft > preorderRight) {
            return null;
        }
        // 构建根节点
        TreeNode root = new TreeNode(preorder[preorderLeft]);
        // 在中序遍历中找到根节点索引
        int rootIndex = inorderMap.get(preorder[preorderLeft]);
        // 得到左子树个数
        int leftSize = rootIndex - inorderLeft;
        root.left = dfs(preorder, inorderMap, preorderLeft + 1, preorderLeft + leftSize, inorderLeft, rootIndex - 1);
        root.right = dfs(preorder, inorderMap, preorderLeft + leftSize + 1, preorderRight, rootIndex + 1, inorderRight);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) {
            return null;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return dfs(preorder, map, 0, preorder.length - 1, 0, inorder.length - 1);
    }

}
